package de.koller.million.enc.network;

import de.koller.oceanFramework.OceanException;
import de.koller.oceanFramework.thread.buffer.Buffer;
import de.koller.oceanFramework.thread.buffer.BufferReceiver;
import de.koller.oceanFramework.thread.buffer.BufferSender;
import java.net.ServerSocket;
import java.net.Socket;

public class Connection extends Thread {
	public static final int PORT = 7570;
	private final Socket socket;
	
	private BufferReceiver receiver;
	private BufferSender sender;

	private final Buffer<Object> received = new Buffer<>();
	private final Buffer<Object> toSend = new Buffer<>();
	
	public Connection( Socket socket ) {
		this.socket = socket;
		
		receiver = new BufferReceiver( socket, received );
		sender = new BufferSender( socket, toSend );
		
		sender.start();
		receiver.start();
	}

	@Override
	public void run() {
		
	}
		
	public static Connection listenForConnection( ServerSocket ss ) {
		try {
			Socket s = ss.accept();
			Connection c = new Connection( s );
			c.start();
			return c;
		} catch( Exception ex ) {
			throw new OceanException( ex );
		}
	}
	
	public static Connection startConnection( String ip ) {
		try {
			System.out.println( "connect to: " + ip );
			Socket s = new Socket( ip, PORT );
			Connection c = new Connection( s );
			c.start();
			return c;
		} catch( Exception ex ) {
			throw new OceanException( ex );
		}
	}

	public Buffer<Object> getReceived() {
		return received;
	}

	public Buffer<Object> getToSend() {
		return toSend;
	}
	
}
